package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.AreaInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.RedpUpmpUtil;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.SortUtil;
import cc.rengu.redp.bizimpl.upmp.dao.AreaInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.AreaInfo;
import cc.rengu.redp.bizimpl.upmp.service.AreaInfoService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiuYuLiang.LL
 */
@Service
@DS("upmp")
public class AreaInfoServiceImpl extends ServiceImpl<AreaInfoMapper, AreaInfo> implements AreaInfoService {
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Override
    public IPage<AreaInfo> findByPage(QueryRequest request, AreaInfo info) {
        try {
            LambdaQueryWrapper<AreaInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(info.getAreaCode())) {
                queryWrapper.like(AreaInfo::getAreaCode, info.getAreaCode());
            }
            if (StringUtils.isNotBlank(info.getAreaName())) {
                queryWrapper.like(AreaInfo::getAreaName, info.getAreaName());
            }
            queryWrapper.orderByDesc(AreaInfo::getCreateTime);
            Page<AreaInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }
    @Override
    @Transactional
    public void create(AreaInfo entity) {
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        entity.setStatus(BusinessContainer.data_sta_01);
        entity.setAuditStatus(BusinessContainer.status_02);
        entity.setOprId(user.getId());
        entity.setCrtOrgId(user.getOrgCode());
        entity.setCreateTime(lastUpddt);
         entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);
        this.baseMapper.insert(entity);
    }
    @Override
    @Transactional
    public void update(AreaInfo entity) {
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        // 修改
        entity.setAuditStatus(BusinessContainer.status_42);
         entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);
        this.baseMapper.updateById(entity);
    }
    @Override
    @Transactional
    public void cancel(String id) {
        // 注销
        AreaInfo entity = this.getById(id);
        entity.setStatus(BusinessContainer.data_sta_03);
        entity.setAuditStatus(BusinessContainer.status_12);
        this.baseMapper.updateById(entity);
    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(list);
    }
    @Override
    public  List<Map<String, Object>>areaInfoSelect2(String q, String regionLevel, String parentCode) {
        Map<String, String> paramMap = new HashMap<>();
        if (StringUtils.isNotBlank(q)) {
            paramMap.put("q", q);
        }
        if (StringUtils.isNotBlank(parentCode)) {
            paramMap.put("parentCode", parentCode);
        }
        if (BusinessContainer.REGION_LEVEL_PROVINCE.equals(regionLevel)) {
            List<Map> list = this.baseMapper.getProvinceAreaInfos(paramMap);
            List<Map<String, Object>> items = Lists.newArrayList();
            if (null != list && list.size() > 0) {
                for (Map map : list) {
                    Map<String, Object> item = Maps.newHashMap();
                    item.put("id", map.get("AREA_CODE"));
                    item.put("name", map.get("AREA_NAME"));
                    item.put("regionCode", map.get("REGION_CODE"));
                    items.add(item);
                }
            }
            return items;
        } else if (BusinessContainer.REGION_LEVEL_CITY.equals(regionLevel)) {
            List<Map> list = this.baseMapper.getCityAreaInfos(paramMap);
            List<Map<String, Object>> items = Lists.newArrayList();
            if (null != list && list.size() > 0) {
                for (Map map : list) {
                    Map<String, Object> item = Maps.newHashMap();
                    item.put("id", map.get("AREA_CODE"));
                    item.put("name", map.get("AREA_NAME"));
                    items.add(item);
                }
            }
            return items;
        }
        return null;
    }

    @Override
    public String findNameByCode(String code) {
        LambdaQueryWrapper<AreaInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AreaInfo::getAreaCode,code);
        List<AreaInfo> list = this.list(queryWrapper);
        String name = "";
        if (list != null && list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                AreaInfo ai = list.get(0);
                name = ai.getAreaName();
            }
        }
        return name;
    }

    @Override
    public Map<String, Object> areaInfoSelect2List(QueryRequest request, String q) {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        //q的格式为  EQ_instId & CN_feeCd_OR_feeName & EQ_pCalType
        q = q.replaceAll("&amp;", "&");
        if (null == q) {
            return null;
        }
        LambdaQueryWrapper<AreaInfo> wrapper = new LambdaQueryWrapper<>();
        String instId = "";
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            wrapper.or(wp -> {
                wp.likeRight(AreaInfo::getAreaCode, param[0])
                .or().likeRight(AreaInfo::getAreaName, param[0]);
            });
        }
        wrapper.eq(AreaInfo::getStatus,  BusinessContainer.data_sta_01);

        Page<AreaInfo> page = new Page<>();
        SortUtil.handlePageSort(request, page, true);
        Page<AreaInfo> page1 = this.page(page, wrapper);
        List<AreaInfo> listx = page1.getRecords();
        Map<String, Object> maps = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();
        List<Object> list = new ArrayList<Object>();
        for (int i = 0; i < listx.size(); i++) {
            AreaInfo ai = listx.get(i);
            map = new HashMap<String, String>();
            map.put("id", ai.getAreaCode());
            map.put("name", ai.getAreaName());
            list.add(map);
        }
        maps.put("results", list);
        maps.put("total", page1.getTotal());
        int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
        if (pageIndex == page1.getTotal()) {
            maps.put("more", false);
        } else {
            maps.put("more", true);
        }
        return maps;
    }
}
